<template> 
    <span>
        <span v-if="licenseInfo"></span>
        <ClientSocket v-if="licenseInfo&&licenseInfo.data&&licenseInfo.data.wsClient" 
        :url="licenseInfo.data.wsClient"
        :clientId="licenseInfo.appInfo.id"
        :orgId="userStore.orgId" />
        <update-version v-if="licenseInfo&&licenseInfo.data&&licenseInfo.data.canUpdated"></update-version>  
    </span>
</template>

<script setup>
let license="";
let appInfo={};
const networkStatus = ref(true)
if(window.electronAPI){
   getLicense(); 
} 
import { getCurrentInstance,ref, defineProps,onMounted } from 'vue';
import { useUserStore } from '../stores/user'
import { useLicenseStore } from '../stores/license'
import { useThemeStore } from '../stores/theme'
import { clientCheck,clientAuth } from '../api/index' 
import CryptoJS from 'crypto-js';
import Base64 from 'crypto-js/enc-base64'
const app = getCurrentInstance()
const userStore = useUserStore() 
const licenseStore = useLicenseStore()   
const themeStore = useThemeStore()   
const props = defineProps({
  onClick: Function
});
const licenseInfo=ref(null);


async function getLicense(){  
  license= await window.electronAPI.getLicenseInfo()
  appInfo= await window.electronAPI.getAppInfo() 
  let datainfo=decrypt(license)
  if(datainfo){
    licenseInfo.value=JSON.parse(datainfo);
  }
   //在线校验
  setTimeout(function(){
    getMyServerLicense();
  },3000) 
 }
//解密
const iv = "license1"
const keyStr = "parkview"
// 十六位十六进制数作为密钥
const SECRET_KEY = CryptoJS.enc.Utf8.parse("parkview");
// 十六位十六进制数作为密钥偏移量
const SECRET_IV = CryptoJS.enc.Utf8.parse("license1");
function encrypt(data) { 
  if (typeof data === "object") {
    try {
      // eslint-disable-next-line no-param-reassign
      data = JSON.stringify(data);
    } catch (error) {
      console.log("encrypt error:", error);
    }
  }
  const dataHex = CryptoJS.enc.Utf8.parse(data);
  const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString();
}


/**
 * 解密方法
 * @param data
 * @returns {string}
 */
function decrypt(data) {
  if(!data){
    return "";
  }
  const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
} 
//在线验证
async function getMyServerLicense(){  
  if(appInfo&&appInfo!="{}"){
    clientCheck({appInfo:JSON.parse(appInfo)}).then(res => {
      if(res.code=='200'&&res.data){
        let client=res.data.client 
        if(!res.data.auth){
          client.status="-1"
        }
        if(client){
          licenseInfo.value=client;
          license=encrypt(client)
          if(client.data){
             saveLicense(license,client.orgId,client.data.config)
          }else{
             saveLicense(license,client.orgId,client.data)
          }
          licenseStore.setLicenseInfo(client)
          licenseStore.setUrl(res.data.url)
        } 
        if(!res.data.auth){
          if(res.data.url&&licenseStore.license){
            setTimeout(function(){
               app?.proxy?.$Bus.emit('ShowThemeWebURL', {url:res.data.url})
            },2000) 
          }
        }
        //有默认的服务地址
        if(client.data&&client.data.config&&client.data.config.themeUrl){
          if(themeStore.themeUrl!=client.data.config.themeUrl){
            themeStore.setThemeUrl(client.data.config.themeUrl)
             setTimeout(function(){
               app?.proxy?.$Bus.emit('ShowThemeWebURL', {url:client.data.config.themeUrl})
            },2000) 
          } 
        }
        //
        if(client.data&&client.data.config&&('apiHost' in client.data.config) &&client.data.config.apiHost){
          if(userStore.apiHost!=client.data.config.apiHost){
            userStore.setApiHost(client.data.config.apiHost)
          } 
        }
      }
    })
  } 
}
async function saveLicense(license,orgId,config){ 
  if(!config){
    config={};
  }
  config.License=license;
  if(orgId){
    config.orgId=orgId; 
  } 
  await window.electronAPI.setLicense(config) 
}
onMounted(() => {  
  if(!navigator.onLine){
      app?.proxy?.$Bus.on('NetWorkReload', function(content){ 
        if(window.electronAPI){
          getLicense();
        } 
      });  
  }
}); 
onUnmounted(() => {
  app?.proxy?.$Bus.off("LicenseReg",function(){});
  app?.proxy?.$Bus.off("NetWorkReload",function(){});
});
app?.proxy?.$Bus.on('LicenseReg', function(content){
  clientAuth({appInfo:appInfo,license:content}).then(res => {
     if(res.code=='200'&&res.data){
      if(res.data.auth){ 
        let client=res.data.client 
        licenseInfo.value=client;
        license=encrypt(client)
        if(client){ 
          saveLicense(license,client.orgId,client.data.config)
        } 
        licenseStore.setLicenseInfo(client)
        licenseStore.setUrl(res.data.url)
      }
      app?.proxy?.$Bus.emit('SystemInfoMsg', {msg:res.message})
     }else{ 
      app?.proxy?.$Bus.emit('SystemInfoMsg', {msg:res.message})
     }
  });
}); 
</script>

<style scoped> 
</style>